#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
功能：harbor所有项目的所有的image的tag超过10将会被清理
默认所有image都有tag,不考虑没有tag的image
"""
import requests
from datetime import datetime
import logging

requests.packages.urllib3.disable_warnings()


class CleanHarborImageTags:
    def __init__(self):
        self.base_url = "https://10.0.0.37/api/v2.0/{}"
        self.headers = {"Content-Type": "application/json"}
        self.auth = ("admin", "Harbor12345")
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.INFO)

    def get_project_list(self):
        """ 获取项目列表 """
        project_list = []
        response = requests.get(self.base_url.format('projects'), auth=self.auth, verify=False, headers=self.headers)
        for num in range(0, len(response.json())):
            project_list.append(response.json()[num]['name'])
        return project_list

    def get_images(self, projectname):
        """ 获取某项目中image列表 """
        images_list = []
        images_url = self.base_url.format("/projects/{}/repositories?page_size=100".format(projectname))
        response = requests.get(images_url, auth=self.auth, verify=False, headers=self.headers)
        if len(response.json()) != 0:
            for num in range(len(response.json())):
                images_list.append(response.json()[num]['name'])
        return images_list

    def get_tags(self, projectname, imagename):
        """获取tag列表"""
        tag_list = []
        tag_url = self.base_url.format(
            "projects/{}/repositories/{}/artifacts?page_size=100".format(projectname, imagename.split('/')[-1]))
        response = requests.get(tag_url, auth=self.auth, verify=False, headers=self.headers)
        if len(response.json()) != 0:
            for num in range(0, len(response.json())):
                date_obj = str(datetime.strptime(response.json()[num]['push_time'], "%Y-%m-%dT%H:%M:%S.%fZ"))
                target_tag = date_obj.replace('-', '').replace(':', '').replace(' ', '').replace('.', '') + "*" + \
                             response.json()[num]['tags'][0]['name']
                tag_list.append(target_tag)
        tag_list.sort()
        return tag_list

    def del_tags(self, projectname, imagename, tagname):
        tag_url = self.base_url.format(
            "projects/{}/repositories/{}/artifacts/{}".format(projectname, imagename, tagname))
        response = requests.delete(tag_url, auth=self.auth, verify=False, headers=self.headers)
        logging.info("是否删除成功：{}".format(response.status_code))

    def run(self):
        project_list = self.get_project_list()
        for projectname in project_list:
            images_list = self.get_images(projectname=projectname)
            for image in images_list:
                logging.info("{}项目的{}镜像清理".format(projectname, image))
                tag_list = self.get_tags(projectname=projectname, imagename=image)
                tag_num = len(tag_list)
                # tag_list 大于10 则按照时间顺序删除
                while tag_num > 10:
                    tag_list = self.get_tags(projectname=projectname, imagename=image)
                    logging.info("{}项目的{}镜像进行删除tag:{}".format(projectname, image, tag_list[0].split('*')[-1]))
                    self.del_tags(projectname=projectname, imagename=image.split('/')[-1],
                                  tagname=tag_list[0].split('*')[-1])
                    tag_list.remove(tag_list[0])
                    tag_num = len(tag_list)


if __name__ == '__main__':
    spider = CleanHarborImageTags()
    spider.run()
